'''
复星乐享一生长期百万医疗险（5年期）
'''
import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper
from urllib.parse import urlencode

class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "复星乐享一生长期百万医疗险（5年期）"

    #生成产品数据
    def genProductInfo(self):

        plan = {

            # 年龄段
            "year":[ str(i) for i in range(50) ],
            # M 男 F 女
            "gender":["M","F"],
            #保险期限
            "expire":["5年"],
            #交费方式 0C 趸交 3年 5 年
            "interval":["0C","3","5"],
            #有无社保
            "socialSec":["Y","N"]

        }


        introduce = {

            "住院医疗保险金":"200w",
            "恶性肿瘤医疗保险金":"200w",
            "垫付住院费用":"支持",
            "就医绿色通道":"支持"
        }

        data = "'" + json.dumps( introduce,ensure_ascii=False) + "'"


        for v in product( plan["year"],plan["gender"],plan["expire"],plan["interval"],plan["socialSec"]):


            #写入数据库
            self.mysql.cursor.execute( domain[self.name]["insert_sql"].format( v[0],v[1],v[2],v[3],v[4],data))

            self.mysql._conn.commit()

            print(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4], data))

    #执行爬虫
    def requestJson(self,dt=None):

        print( dt )

        data = {

            "BTsc003000a000017739_TextAge": ""+dt["year"]+"Y",
            "BTsc003000a000017740_Sex": dt["gender"],
            "BTsc003000a000017741_Period": "5Y",
            "BTsc003000a000017742_FeeYear": dt["interval"]+"Y" if "0C" not in dt["interval"] else "0C",
            "BTsc003000a000017870_Occup": "1 - 4",
            "BTsc003000a000017743_Plan": "A_SY" if dt["socialSec"] == "Y" else "B_SN",
            "duty": "226101002001 - 2000000, 226101002002 - 2000000, 226101002003 - 2000000, 226101002004 - 0, 226101002005 - 0",
            "productid": "226101002",
            "complicatedFlag": "N",
            "channelSn": "agent_pc",
            "userTrack":"",
            "pointExchangeFlag": "N"
        }

        r = requests.post( url =domain[self.name]["url"],headers=domain[self.name]["header"],data=urlencode(data).replace("+",''))

        try:
            if r.status_code ==200 and r.json()["msg"] == "成功！":

                price = Helper.decimalParse( r.json()["data"]["productPrice"] )

                data = {

                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }

                self.mysql.updatePrice( data )

            else:

                data = {

                    "name": self.name,
                    "id": dt["id"],
                    "state": 3
                }
                self.mysql.randTask(data)

        except :

            pass


    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)
